import cgi
import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from simple_validation import *

class <%= @table.TableName %>(db.Model):
    <% for col in @table.Columns %>   
    <%= col.ColumnName %> = <%= @gae_prop_from_dot_net_type[col.DataType.to_s()] %> #<%= col.DataType %>
    <% end %>

class <%= @table.TableName %>Repo:
	def get_all(self):
		records = <%= @table.TableName %>.all()
		return records
		
	def add(self,aRecord):
		aRecord.put()
		
	def update(self,aRecord):
		aRecord.put()

	def delete(self,key):
		aRecord = <%= @table.TableName %>.get(key)
		aRecord.delete()

	def get(self,key):
		aRecord = <%= @table.TableName %>.get(key)
		return aRecord
		
#================================================================================		
		
def write(aHandler, value):
    aHandler.response.out.write(value)
    
#================================================================================

def renderHtmlView(aHandler, aTemplate, data):
    path = os.path.join(os.path.dirname(__file__), aTemplate)
    write(aHandler, template.render(path, data))
    
#================================================================================

class <%= @table.TableName %>ListHandler(webapp.RequestHandler):
    def get(self):
      records = <%= @table.TableName %>Repo().get_all()
      template_values = {'records': records}
      renderHtmlView(self, '<%= @table.TableName %>_list.html', template_values)

#================================================================================

class <%= @table.TableName %>EditHandler(webapp.RequestHandler):
    def get(self):
      action = self.request.get("action")
      
      if action == "edit":
        recordID = self.request.get("id")
        record = <%= @table.TableName %>Repo().get(recordID)
        template_values = {'record': record}
      elif action == "new":
        template_values = {}
      else:
        raise Exception("action is not defined or not valid.")
  
      renderHtmlView(self, "<%= @table.TableName %>_edit.html", template_values)

#================================================================================

class <%= @table.TableName %>EditSaveHandler(webapp.RequestHandler):
	def post(self):
		key = self.request.get('key')

		# get form values...
		<% for col in @table.Columns %>
		<%= col.ColumnName %> = self.request.get('<%= col.ColumnName %>')
		<% end %>
		
		v = Validator()
		<% for col in @table.Columns %>
		<% if col.AllowDBNull==false %>
		v.check_required_field("<%= col.ColumnName %>","<%= get_human_db_ref(col.ColumnName) %> is required", <%= col.ColumnName %>)
		<% end %>

		<% if col.DataType.to_s() == "System.Int32" %> 
		v.check_int_field("<%= col.ColumnName %>","<%= get_human_db_ref(col.ColumnName) %> must contain a valid integer.", <%= col.ColumnName %>)
		<% end %>
		<% if col.DataType.to_s() == "System.Single" %> 
		v.check_float_field("<%= col.ColumnName %>","<%= get_human_db_ref(col.ColumnName) %> must contain a valid number.", <%= col.ColumnName %>)
		<% end %>
		
		
		<% end %>
		
		if len(v.errors) > 0:
			template_values = {'errors': v.errors}
			renderHtmlView(self, 'generic_errors.html', template_values)
		else:	
			# do conversions...
			<% for col in @table.Columns %>
			<% if col.DataType.to_s() == "System.Int32" %> 
			<%= col.ColumnName %> = int(<%= col.ColumnName %>)
			<% end %>
			<% if col.DataType.to_s() == "System.Single" %> 
			<%= col.ColumnName %> = float(<%= col.ColumnName %>)
			<% end %>
			<% end %>
			
			if len(key) > 0: 
				record = <%= @table.TableName %>Repo().get(key)    
			else:
				record = <%= @table.TableName %>()
	  
			<% for col in @table.Columns %>
			record.<%= col.ColumnName %> = <%= col.ColumnName %>
			<% end %>
			
			t = <%= @table.TableName %>Repo()
			if len(key) > 0:
				t.add(record)
			else:
				t.update(record)
	  
			close_record = self.request.get('close_record')
			if(close_record=="1"):
				self.redirect("list")
			else:
				self.redirect("edit?id=" + str(record.key()) + "&action=edit")   
	 
#================================================================================

class <%= @table.TableName %>DeleteHandler(webapp.RequestHandler):
    def get(self):
		recordID = self.request.get("id")
		t = <%= @table.TableName %>Repo()
		t.delete(recordID)
		self.redirect("list")
